// subPackages/packageA/debotrDetail/debtorDet.ts
import { getPartnerPageInfoApi, getEmployeePageInfoApi, getBusinessInfoApi, getCountInfoApi, getBusinessCountApi, judicialInvolvementCountApi, getOperationalRiskApi } from "../../../api/debtor";
import { formatCurrency, replaceTime, debtorPrice, checkPermission, zcc } from "../../../utils/util"

Page({
  /**
   * 页面的初始数据
   */
  data: {
    scopeMax: 43, // 经营范围截取的字数
    safeBottom: 0,
    loading: false,
    debtorId: "",
    companyName: "",
    companyId: "",
    binfo: {
      phoneNumber: undefined,
      email: undefined
    },//工商信息
    partnerList: [

    ],// 股东列表
    employeeList: [

    ], // 人员列表
    // 切换展示 曾用名
    originalNameFlag: false,
    // 是否展开经营范围
    scopeFlag: false,
    previewData: {
      clueNum: "", // 财产线索(条)
      clueAmount: "",// 财产线索价值(万元)
      sxNum: "", // 涉诉线索（条）
      bcNum: "" // 次债务人线索
    },
    navbarHeight: getApp().globalData.safeNavHeight,
    tabList: [
      { name: "基本信息", id: 1, permission: "basicinfo", isPermitted: true },
      { name: "司法涉诉", id: 2, permission: "shesu", isPermitted: true },
      { name: "经营风险", id: 3, permission: "risk", isPermitted: true },
    ],
    activeTab: 1,
    // 基本信息分类
    basicTabs: [
      { key: "businessinfo", name: "工商信息", num: "", path: "/subPackages/packageA/debtorBaseInfo/businessinfo/businessinfo" },
      { key: "countPartner", name: "股东信息", num: 0, path: "/subPackages/packageA/debtorBaseInfo/shareholder/shareholder" },
      { key: "countEmployee", name: "主要人员", num: 0, path: "/subPackages/packageA/debtorBaseInfo/mainperson/mainperson" },
      { key: "countInvestInfo", name: "对外投资", num: 0, path: "/subPackages/packageA/debtorBaseInfo/odi/odi" },
      { key: "countChangeRecord", name: "变更记录", num: 0, path: "/subPackages/packageA/debtorBaseInfo/changerecord/changerecord" },
      { key: "countBranch", name: "分支机构", num: 0, path: "/subPackages/packageA/debtorBaseInfo/branch/branch" }
    ],
    basicTabsArray: [],
    // 司法涉诉分类
    shesuTabs: [
      { key: "bcNum", name: "次债务人线索", num: 0, path: "/subPackages/packageA/shesu/secondaryDebtorClue/secondaryDebtorClue" },
      { key: "sxNum", name: "涉诉信息", num: 0, path: "/subPackages/packageA/shesu/shesuList/shesuList" },
      { key: "countReorganization", name: "破产重整企业", num: 0, path: "/subPackages/packageA/shesu/bankruptList/bankruptList" },
      { key: "zxNum", name: "失信执行人信息", num: 0, path: "/subPackages/packageA/shesu/executorInfo/executorInfo" },
      { key: "countLimitHighconsume", name: "限制高消费信息", num: 0, path: "/subPackages/packageA/shesu/consumptionInfo/consumptionInfo" },
      { key: "countFinalCase", name: "终本案件", num: 0, path: "/subPackages/packageA/litigation/litigation" },
      { key: "countRegister", name: "立案信息", num: 0, path: "/subPackages/packageA/litigation/litigation" },
      { key: "countNotice", name: "开庭公告", num: 0, path: "/subPackages/packageA/litigation/litigation" },
      { key: "countAnnouncement", name: "法院公告", num: 0, path: "/subPackages/packageA/litigation/litigation" },
      { key: "countEquityFreeze", name: "司法协助股权冻结", num: 0, path: "/subPackages/packageA/shesu/freeze/freeze" },
      { key: "countAssistanceUnfreeze", name: "司法协助解除冻结", num: 0, path: "/subPackages/packageA/shesu/unfreeze/unfreeze" },
      { key: "countAuction", name: "司法拍卖", num: 0, path: "/subPackages/packageA/shesu/judicialAuction/judicialAuction" },
    ],
    shesuTabsArray: [],
    colors: ['#91A8DE', '#DEC091', '#91BEDE', '#91DEAB', '#DE9191'],
    // 经营风险分类
    riskTabs: [
      { key: "countOperateException", name: "经营异常", num: 0, path: "/subPackages/packageA/operatingRisk/abnormal/abnormal" },
      { key: "countSeriousViolation", name: "严重违法", num: 0, path: "/subPackages/packageA/operatingRisk/seriousIllegality/seriousIllegality" },
      { key: "countOweTaxNotice", name: "欠税公告", num: 0, path: "/subPackages/packageA/operatingRisk/taxArrears/taxArrears" },
      { key: "countMajorViolation", name: "重大税收违法", num: 0, path: "/subPackages/packageA/operatingRisk/seriousTaxIllegality/seriousTaxIllegality" },
      { key: "countStockPledge", name: "股权出质", num: 0, path: "/subPackages/packageA/operatingRisk/stockRightPledage/stockRightPledage" },
      { key: "countOperationMpledge", name: "动产抵押", num: 0, path: "/subPackages/packageA/operatingRisk/chattelMortgage/chattelMortgage" },
      { key: "countLandMortgage", name: "土地抵押", num: 0, path: "/subPackages/packageA/operatingRisk/landMortgage/landMortgage" },
      { key: "countLandaucParty", name: "土地拍卖", num: 0, path: "/subPackages/packageA/operatingRisk/landAuction/landAuction" },
      { key: "countOperationLiquidation", name: "清算信息", num: 0, path: "/subPackages/packageA/operatingRisk/liquidation/liquidation" },
    ],
    riskTabsArray: [],
    tabbarSticky: false,
    scrollTopBoxHeight: 0,
    toView: "", // 锚点定位的id
    sivOffset: 80

  },
  onPhoneClick() {
    zcc.callPhone(this.data.binfo.phoneNumber)
  },
  onEmailClick() {
    zcc.copyToClipboard(this.data.binfo.email, '邮箱已复制')
  },
  // 展示更多经营范围
  showScope() {
    this.setData({
      scopeFlag: true
    })
    this.getScrollTopHeight();
  },
  hideScope() {
    this.setData({
      scopeFlag: false
    })
    this.getScrollTopHeight();
  },
  // 切换展示曾用名
  toggleOriginName() {
    let originalNameFlag = this.data.originalNameFlag;
    this.setData({
      originalNameFlag: !originalNameFlag
    })
  },
  // 点击拨打电话
  makeCall(e: any) {
    const phonenumber = e.currentTarget.dataset.phonenumber;
    if (!phonenumber) return;
    wx.makePhoneCall({
      phoneNumber: phonenumber
    })
    // wx.showModal({
    //   title: "提示",
    //   content: "确定拨打电话" + phonenumber + "吗？",
    //   success(res) {
    //     if (res.confirm) {
    //       wx.makePhoneCall({
    //         phoneNumber: phonenumber
    //       })
    //     }
    //   }
    // })
  },
  // 复制邮箱地址
  copyEmail(e: any) {
    const text = e.currentTarget.dataset.email;
    if (!text) return;
    wx.setClipboardData({
      data: text
    })
  },
  // 线索统计- 财产线索跳转到财产线索页
  skipToCluePage() {
    // ?companyId=" + this.data.companyId + "&companyName=" + this.data.companyName
    let app = getApp();
    app.globalData.companyPara = {
      debtorId: this.data.debtorId,
      companyName: this.data.companyName
    }
    wx.switchTab({
      url: "/pages/propertyClue/propertyClue"
    })
  },
  // 涉诉线索-跳转到涉诉信息页面
  shesuSkip() {
    wx.navigateTo({
      url: "/subPackages/packageA/shesu/shesuList/shesuList?debtorId=" + this.data.debtorId + "&companyName=" + this.data.companyName
    })
  },
  // 获取工商信息
  async getBusinessInfo() {
    let para = {
      name: this.data.companyName
    }
    return getBusinessInfoApi(para).then((res: any) => {
      let content = res.content;
      content.scope = content.scope.replace('^', "");
      content.registCapiDesc = content.registCapiDesc.replace("人民币元", "人民币");
      content.registCapi = formatCurrency(content.registCapi);
      content.startDate = replaceTime(content.startDate);
      if (content.originalName) {
        content.originalName = content.originalName.replace(/[|，]/g, ",").split(",");
      }
      if (res.code === '000') {
        let max = this.data.scopeMax;
        if (content.scope && content.scope.length > max) {
          content.sliceScope = content.scope.slice(0, max) + '...';
        }

        this.setData({
          binfo: content,
          companyId: content.companyId
        })
        this.getPartnerList();
        this.getEmployeeList();
      }
    })
  },
  // 债务人财产线索统计
  async getCountInfo() {
    const res: any = await getCountInfoApi({ id: this.data.debtorId })
    let content = res.content;
    content.clueAmount = debtorPrice(content.clueAmount);
    this.setData({
      previewData: content
    })
  },
  // 获取股东列表
  getPartnerList() {
    let para = {
      page: 1,
      perPage: 9999,
      companyId: this.data.companyId
    }
    getPartnerPageInfoApi(para).then((res: any) => {
      if (res.code === '000') {
        let contentList = res.content.list || [];
        contentList.forEach((item: any, index: number) => {
          item.firstName = item.stockName.slice(0, 1);
          item.stockPercent = item.stockPercent ? parseFloat(item.stockPercent).toFixed(2) + '%' : '-';
        });
        this.setData({
          partnerList: contentList,
        });
      }
    })
  },
  // 获取人员列表
  getEmployeeList() {
    let para = {
      page: 1,
      perPage: 9999,
      companyId: this.data.companyId,
    }
    getEmployeePageInfoApi(para).then((res: any) => {
      if (res.code === '000') {
        let contentList = res.content.list || [];
        contentList.forEach((item: any, index: number) => {
          item.firstName = item.name.slice(0, 1);
        });
        this.setData({
          employeeList: contentList,
        });
      }
    })
  },
  // tab 切换
  tabToggle(e: any) {
    let id = e.currentTarget.dataset.id;
    this.setData({
      activeTab: id,
      toView: "aid" + id
    })
  },
  // 获取 基本信息分类统计
  async getBasicNum() {
    return getBusinessCountApi({ name: this.data.companyName }).then((res: any) => {
      if (res.code === '000') {
        let content = res.content;
        this.data.basicTabs.forEach((item) => {
          if (content[item.key] !== undefined) {
            item.num = content[item.key];
          }
        })
        this.toArray("basicTabs");
      }
    })
  },
  // 获取 司法涉诉 分类统计
  async getShesuNum() {
    return judicialInvolvementCountApi({ name: this.data.companyName }).then((res: any) => {
      if (res.code === '000') {
        let content = res.content;
        let previewData = this.data.previewData;
        this.data.shesuTabs.forEach((item) => {
          if (content[item.key] === undefined) {
            item.num = previewData[item.key];
          } else {
            item.num = content[item.key];
          }
        })
        this.toArray("shesuTabs");
      }
    })
  },
  // 获取 经营风险 分类统计
  async getRiskNum() {
    return getOperationalRiskApi({ name: this.data.companyName }).then((res: any) => {
      if (res.code === '000') {
        let content = res.content;
        this.data.riskTabs.forEach((item) => {
          if (content[item.key] !== undefined) {
            item.num = content[item.key];
          }
        })
        this.toArray("riskTabs");
      }
    })
  },
  // 分组
  toArray(key: string) {
    let keyValue = this.data[key];
    let results: any[] = [];
    let len = keyValue.length;
    let rows = Math.ceil(len / 4);
    for (let i = 0; i < rows; i++) {
      results.push(keyValue.slice(i * 4, i * 4 + 4))
    }
    // console.log(results, "results")
    this.setData({
      [key + 'Array']: results
    })
  },
  async initGet() {
    await this.getCountInfo();
    return this.getShesuNum();
  },
  // 跳转到首页
  skipHome() {
    wx.switchTab({
      url: "/pages/index/index"
    })
  },
  // 下拉刷新
  async refreshHandle() {
    this.setData({
      loading: true
    })
    const that = this
    zcc.getUserProfile({
      onSuccess: async () => {
        const promise1 = that.getBusinessInfo();
        const promise2 = that.initGet();
        const promise3 = that.getBasicNum();
        const promise4 = that.getRiskNum();
        await Promise.all([promise1, promise2, promise3, promise4]);
        that.setPermission();
      },
      onFinally: () => {
        that.setData({
          loading: false
        })
      }
    })

  },
  // 股东跳转
  partnerSkip() {
    wx.navigateTo({
      url: "/subPackages/packageA/debtorBaseInfo/shareholder/shareholder" + "?companyId=" + this.data.companyId
    })
  },
  // 人员跳转
  employeeSkip() {
    wx.navigateTo({
      url: "/subPackages/packageA/debtorBaseInfo/mainperson/mainperson" + "?companyId=" + this.data.companyId
    })
  },
  // 基础信息 跳转
  basicInfoSkip(e: any) {
    let num = e.currentTarget.dataset.num;
    let path = e.currentTarget.dataset.path;
    let key = e.currentTarget.dataset.key;
    if (num <= 0 && key !== 'businessinfo') return;
    let url = path;
    if (key === "businessinfo") {
      url = path + "?name=" + this.data.companyName
    }
    if (key === 'countPartner' || key === 'countEmployee' || key === 'countInvestInfo' || key === 'countChangeRecord' || key === 'countBranch') {
      url = path + "?companyId=" + this.data.companyId
    }
    wx.navigateTo({
      url: url
    })
  },
  // 司法涉诉 跳转
  shesuInfoSkip(e: any) {
    let num = e.currentTarget.dataset.num;
    let path = e.currentTarget.dataset.path;
    let key = e.currentTarget.dataset.key;
    if (num <= 0) return;
    let url = path;
    wx.navigateTo({
      url: url + `?debtorId=${this.data.debtorId}&companyName=${this.data.companyName}&companyId=${this.data.companyId}&scene=${key}`
    })
  },
  // 经营风险跳转
  riskInfoSkip(e: any) {
    let num = e.currentTarget.dataset.num;
    let path = e.currentTarget.dataset.path;
    // let key = e.currentTarget.dataset.key;
    if (num <= 0) return;
    let url = path;
    wx.navigateTo({
      url: url + `?companyId=${this.data.companyId}`
    })
  },
  // scroll 滚动
  onScroll(e: any) {
    // console.log(e.detail.scrollTop, "e.detail.scrollTop")
    if (this.data.tabList.length == 0) return;
    this.getScrollTopHeight();
    const scrollTop = e.detail.scrollTop;
    if (scrollTop >= this.data.scrollTopBoxHeight) {
      // 吸顶
      this.setData({
        tabbarSticky: true
      })
    } else {
      // 复位
      this.setData({
        tabbarSticky: false
      })
    }
  },
  // 获取 tabbar 以上元素的高度
  getScrollTopHeight() {
    wx.createSelectorQuery().select("#scrollBoxID").boundingClientRect((res) => {
      // console.log(res.height, "res.height")
      this.setData({
        scrollTopBoxHeight: res.height
      })
    }).exec()
  },
  // 设置 tab-bar 权限
  setPermission() {
    // console.log(getApp().globalData.permissions, "getApp().globalData.permissions")
    let tabList = this.data.tabList;

    // this.setData({
    //   tabList: tabList.filter(item => checkPermission([item.permission]))
    // })
    tabList.forEach((item) => {
      item.isPermitted = checkPermission([item.permission]);
    })
    this.setData({
      tabList: tabList
    })
  },
  // 判断 tab-bar 内容是否展示
  // isPermitted(id: number) {
  //   console.log(this.data.tabList, "this.data.tabList")

  //   const res = this.data.tabList.find(item => {
  //     return item.id === id;
  //   })
  //   console.log(res, "res")
  //   return res;
  // },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(option) {
    // console.log(option, "option")
    this.data.debtorId = option.debtorId || "";
    this.data.companyName = option.companyName || "";
    zcc.getUserProfile({
      loading: true,
      onSuccess: () => {
        this.getBusinessInfo();
        this.initGet();
        this.getBasicNum();
        this.getRiskNum();
        const app = getApp();
        this.setData({
          safeBottom: app.globalData.screenHeight - app.globalData.safeArea.bottom,
          debtorId: this.data.debtorId,
          companyName: this.data.companyName
        })
      },
      onFinally: () => {
        this.setPermission();
      }
    })

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {
    // 设置 tab-bar 权限
    this.setPermission();
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },
  // 页面分享
  // onShareAppMessage() {
  //   let path = "/subPackages/packageA/debotrDetail/debtorDetail?debtorId=" + this.data.companyId + "&companyName=" + this.data.companyname;
  //   let title = this.data.companyName;
  //   const promise = new Promise(resolve => {
  //     setTimeout(() => {
  //       resolve({
  //         title: title,
  //         path: path
  //       })
  //     }, 2000)
  //   })
  //   return {
  //     title: "债务人详情",
  //     path: path,
  //     promise: promise
  //   }
  // }
})